/**
 * Created by DevilsEyes on 2016/6/9.
 */
'use strict';

let focus = null,
    f = 0,
    w = 0,
    h = 0;

const turnX = (a,tx,ty,tz)=>{
    a = -a;
    let x,y,z;
    x = tx * Math.cos(a) + ty * Math.sin(a);
    y = -tx * Math.sin(a) + ty * Math.cos(a);
    z = tz;
    return [x,y,z];
}

const turnY = (a,tx,ty,tz)=>{
    a = -a;
    let x,y,z;
    x = tx * Math.cos(a) + tz * Math.sin(a);
    y = ty;
    z = -tx * Math.sin(a) + tz * Math.cos(a);
    return [x,y,z];
}

class Point {
    constructor(x, y, z) {
        this.init = {
            x: x,
            y: y,
            z: z
        };

        this.x = x;
        this.y = y;
        this.z = z;

        this.vx = 0;
        this.vy = 0;
        this.vz = 0;

        this.ax = 0;
        this.ay = 0;
        this.az = 0;
    }

    get r() {
        let dx = this.x - focus.x;
        let dy = this.y - focus.y;
        let dz = this.z - focus.z;
        return Math.sqrt(dx * dx + dy * dy + dz * dz);
    }

    toCamera() {
        let {abs} = Math;

        return {
            h: this.z * f / abs(this.x - focus.x),
            v: this.y * f / abs(this.x - focus.x),
            r: this.r
        }
    }

    toCanvas() {
        let p = this.toCamera();
        return {
            x: w / 2 + p.v,
            y: h / 2 + p.h
        }
    }

    turnX(a) {
        let [x,y,z] = turnX(a,this.x,this.y,this.z);
        let [vx,vy,vz] = turnX(a,this.vx,this.vy,this.vz);
        this.x = x;
        this.y = y;
        this.z = z;
        this.vx = vx;
        this.vy = vy;
        this.vz = vz;
    }

    turnY(a) {
        let [x,y,z] = turnY(a,this.x,this.y,this.z);
        let [vx,vy,vz] = turnY(a,this.vx,this.vy,this.vz);
        this.x = x;
        this.y = y;
        this.z = z;
        this.vx = vx;
        this.vy = vy;
        this.vz = vz;
    }

    move(x,y,z){
        this.x += x||this.vx;
        this.y += y||this.vy;
        this.z += z||this.vz;
    }

    reverse(){
        var key;
        var set = ['ax','ay','az'];
        for(key of set){
            this[key] = - this[key] * 0.5;
        }
        var set2 = ['vx','vy','vz'];
        for(key of set2){
            this[key] = - this[key];
        }
    }

    refresh() {
        this.x = this.init.x;
        this.y = this.init.y;
        this.z = this.init.z;
    }
}

module.exports = {

    Point,//构造函数

    //初始化函数
    init: (config)=> {
        w = config.canvasWidth;
        h = config.canvasHeight;
        f = config.focalLength;
        focus = config.focus;
    },

    //配置项
    getConfigs() {
        return {
            canvasWidth: w,
            canvasHeight: h,
            focalLength: f,
            focus: focus
        }
    },

//==============快捷方法===================
    //快速创建
    P: (x, y, z)=>new Point(x, y, z),

    //获取焦点
    focus
};